package com.wl.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wl.auth.service.AuthService;
import com.wl.common.core.constant.ConstantSystem;
import com.wl.common.security.utils.JwtTokenUtil;
import com.wl.common.system.dao.SysRoleMapper;
import com.wl.common.system.dao.SysUserMapper;
import com.wl.common.system.dao.SysUserRoleMapper;
import com.wl.common.system.service.impl.SysUserService;
import com.wl.common.system.support.dto.PasswordDTO;
import com.wl.common.system.support.dto.ResetPasswordDTO;
import com.wl.common.system.support.dto.SysUserDTO;
import com.wl.common.system.support.vo.SysUserVO;
import com.wl.system.api.domain.SysUser;
import com.wl.system.api.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.List;

/**
 * @author: wanglin
 * @date: 2024-03-11 周一
 * @Version: 1.0
 * @Description:
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;

//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public void resetPassword(String userId, String password) {
//        Assert.hasText(userId, "账号不能为空");
//        Assert.hasText(password, "密码不能为空");
//        Assert.isTrue(password.matches(ConstantSystem.PASSWORD_REG), "密码至少包含：数字,英文,字符中的两种以上，长度6-16");
//
//        LoginUser loginUser = jwtTokenUtil.getLoginUser(userId);
//        Assert.notNull(loginUser, "账号: " + userId + "不存在！");
//        //验证操作是管理员
//        boolean isAdminFlag = loginUser.getRoles().stream().anyMatch(e -> ConstantSystem.ADMIN.equals(e) || ConstantSystem.SUPER_ADMIN.equals(e));
//        Assert.isTrue(isAdminFlag, "当前操作权限不足");
//        userMapper.resetPassword(userId, passwordEncoder.encode(password));
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetUserPwd(ResetPasswordDTO dto) {
        Assert.isTrue(dto.getPassword().matches(ConstantSystem.PASSWORD_REG), "密码至少包含：数字,英文,字符中的两种以上，长度6-16");
        //验证当前操作是管理员
//        LoginUserDetails loginUser = jwtTokenUtil.getLoginUser();
//        String userName = jwtTokenUtil.getUserName();
//        LoginUserDetails loginUser = loginUserRegistry.getLoginUser(userName);
        this.isAdminValidate();
        //获取重置密码的用户
        SysUser userEntity = userMapper.selectById(dto.getUserId());
        Assert.notNull(userEntity, "用户id: " + dto.getUserId() + "不存在！");
        //不能操作超级管理员
        SysUserVO userVo = userMapper.selectUserAndRoleById(dto.getUserId());
        boolean isSuperFlag = Arrays.stream(userVo.getRoleType().split(",")).anyMatch(e -> ConstantSystem.SUPER_ADMIN.equals(e));
        Assert.isTrue(!isSuperFlag, "当前操作权限不足，不能操作超级管理员");

        userEntity.setPassword(passwordEncoder.encode(dto.getPassword()));
        userMapper.updateById(userEntity);
        jwtTokenUtil.delLoginUser(userEntity.getUserId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatusById(String userId) {
        //管理员操作
        this.isAdminValidate();

        SysUser user = userService.getUserInfo(userId);
        Assert.notNull(user, "账号: " + userId + "不存在");
        Integer status = NumberUtils.INTEGER_ZERO;
        if (NumberUtils.INTEGER_ZERO.equals(user.getStatus())) {
            status = NumberUtils.INTEGER_ONE;
            //若该账号已登录，则不允许访问
            jwtTokenUtil.delLoginUser(user.getUserId());
        }
        userMapper.updateUserStatus(userId, status);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserPwd(PasswordDTO dto) {
        //参数验证
        Assert.isTrue(dto.getNewPassword().matches(ConstantSystem.PASSWORD_REG), "密码至少包含：数字,英文,字符中的两种以上，长度6-16");
        Assert.isTrue(dto.getNewPassword().equals(dto.getConfirmPassword()), "新密码两次输入不一致");
        Assert.isTrue(!dto.getNewPassword().equals(dto.getOldPassword()), "新密码不能和原密码相同");
        //修改
        Assert.hasText(dto.getUserId(), "账号不存在");
        SysUser entity = userMapper.selectByUserId(dto.getUserId());
        Assert.notNull(entity, "账号: " + dto.getUserId() + "不存在");
        Assert.isTrue(passwordEncoder.matches(dto.getOldPassword(), entity.getPassword()), "原密码错误");
        entity.setPassword(passwordEncoder.encode(dto.getNewPassword()));
        userMapper.updateById(entity);
        //修改密码后必须重新登录
        jwtTokenUtil.delLoginUser(entity.getUserId());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUser(SysUserDTO dto) {
        dto.setPassword(passwordEncoder.encode(dto.getPassword()));
        userService.addUser(dto);
    }

    private List<SysUser> validateRepeat(String userId, String name) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(StringUtils.isNotBlank(userId), SysUser::getUserId, userId)
                .eq(StringUtils.isNotBlank(name), SysUser::getName, name);
        return userMapper.selectList(queryWrapper);
    }

    /**
     * 当前操作人必须是管理员
     */
    private void isAdminValidate() {
        LoginUser loginUser = jwtTokenUtil.getLoginUser();
        Assert.notNull(loginUser, "未登录，请先登录");
        boolean isAdminFlag = loginUser.getRoles().stream().anyMatch(e -> ConstantSystem.ADMIN.equals(e) || ConstantSystem.SUPER_ADMIN.equals(e));
        Assert.isTrue(isAdminFlag, "当前操作权限不足");
    }

}
